package com.demo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import com.demo.dao.UserDAO;
import com.demo.entity.User;

public class UserController implements Servlet {
	
	UserDAO userDAO;
	
	@Override
	public void destroy() {
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		userDAO = new UserDAO();
	}

	@Override
	public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html; charset=utf-8");//先设置response
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();	
		PrintWriter out = response.getWriter();

		String contextPath = request.getContextPath();
		String username = null, password = null;

		String action = request.getParameter("action");
		if(action==null) action = "";
		switch (action) {
		case "checkAccount":// 校验账号的唯一性
			resp.setContentType("text/json;charset=utf-8");// 设置客户端收到的内容类型和编码
			Long nums = userDAO.checkAccount(request.getParameter("account"), request.getParameter("accountType"));
			String result = nums>0 ? "{\"code\":-1, \"msg\":\"该账号已被注册\"}" : "{\"code\":0, \"msg\":\"可以使用\"}";
			out.print(result);
			break;

		case "reg":// 注册
			Map<String, String[]> parametertMap = request.getParameterMap();//很厉害，里面放了所有的请求参数！！
			User user = new User();
			try {
				DateConverter dateConverter = new DateConverter();
				dateConverter.setPattern("yyyy-MM-dd");
				ConvertUtils.register(dateConverter, java.util.Date.class);//把String日期转成Date日期
				BeanUtils.populate(user, parametertMap);//把请求参数Map封装到Bean
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(userDAO.save(user)==1) {
				session.setAttribute("username", user.getUsername());
				response.sendRedirect(contextPath+"/index.jsp");
			}
			break;

		case "login":// 登录
			username = request.getParameter("username");
			password = request.getParameter("password");
			if (username != null && password != null) {
				if (username.equals("tom") && password.equals("1")) {
					session.setAttribute("username", username);
					
					//自动登录，要把账号信息存到cookie
					if(request.getParameter("autoLogin")!=null && request.getParameter("autoLogin").equals("1")) {
						Cookie c1 = new Cookie("username", username);
						Cookie c2 = new Cookie("password", password);
						int maxTime = 7*24*60*60;//cookie存一周
						c1.setMaxAge(maxTime);c1.setPath("/");
						c2.setMaxAge(maxTime);c2.setPath("/");
						response.addCookie(c1);
						response.addCookie(c2);
					}
					//在重定向后不能有其他代码
					response.sendRedirect(contextPath+"/index.jsp");
				} else {
					response.sendRedirect(contextPath+"/login.jsp?code=-1");
				}
			}
			break;

		case "logout":// 退出
			if (session.getAttribute("username") != null)
				session.removeAttribute("username");
			response.sendRedirect(contextPath+"/index.jsp");
			break;

		default:
			out.print("500: page error");
			//throw new IllegalArgumentException("Unexpected value: " + request.getParameter("action"));
		}

	}

}
